package com.isoftstone.framework.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.AuthenticationStrategy;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

import java.util.Collection;

/**
 * @Description: 多个realm处理，
 * @Author: guoX
 * @Date: 2019/8/13
 */
public class MyModularRealmAuthenticator extends ModularRealmAuthenticator {

    @Override
    protected AuthenticationInfo doMultiRealmAuthentication(Collection<Realm> realms, AuthenticationToken token) {
        AuthenticationStrategy strategy = getAuthenticationStrategy();
        AuthenticationInfo attempts = strategy.beforeAllAttempts(realms, token);

        AuthenticationException authenticationException = null;
        for (Realm realm : realms) {
            strategy.beforeAttempt(realm,token,attempts);

            if(realm.supports(token)){
                AuthenticationInfo info = null;
                try {
                    info = realm.getAuthenticationInfo(token);

                }catch (AuthenticationException e){
                    authenticationException = e;
                }
                strategy.afterAttempt(realm,token,info,attempts,authenticationException);
            }
        }

        // 如果有异常返回， 直接返回
        if(authenticationException != null){
            throw authenticationException;
        }
        AuthenticationInfo allAttempts = strategy.afterAllAttempts(token, attempts);
        return allAttempts;
    }
}
